#!/bin/bash

if [ ! -n "$1" ];then
  echo "请输入参数" && exit 1
fi

cmdbapi="http://cmdb.oriente.com/api/v1/app"
token="Token aadc518ac30e191c934c6ca181c1248546b4a4d3"
appjson=$(curl -s -H Authorization:"$token" "$cmdbapi/?name=${CI_PROJECT_NAME}&business=$1"|jq '.results')

path=$(pwd)

if [[ "$appjson" =~ "health" ]]; then
  health=$(echo $appjson | jq -r '.[0].health')
  limitmemory=$(echo $appjson | jq -r '.[0].resource.limit_memory')
  requestmemory=$(echo $appjson | jq -r '.[0].resource.request_memory')
  domain=$(echo $appjson | jq -r '.[0].domain'|awk -F ';' '{print $1}')
  echo 当前路径:$path

  echo "---修改health:$health---"
  sed -i "s#/healthcheck#$health#g" $(grep "/healthcheck" -rl ${CI_PROJECT_NAME})
  
  echo "---修改limit memory:$limitmemory---"
  sed -i "/limits:/{n;s/memory: limitsMEM/memory: $limitmemory/g;}" $(grep "limits:" -rl ${CI_PROJECT_NAME})
  
  echo "---修改request memory:$requestmemory---"
  sed -i "/requests:/{n;s/memory: requestsMEM/memory: $requestmemory/g;}" $(grep "requests:" -rl ${CI_PROJECT_NAME})

  if [[ $domain != "null" ]]; then
    echo "---修改${PROJECT_ENV}-ingress:$domain"
    urlName=$(echo $domain|awk -F '.' '{print $1}')
    sed -i "s#${CI_PROJECT_NAME}#$urlName#g" $(find ${CI_PROJECT_NAME}/overlays/${PROJECT_ENV} -name "kustomization.yaml")
  fi
else
  echo "CMDB里没有找到APP,使用默认配置"
fi